<?php

namespace app\api\model;
use app\common\model\UserInfo as UserInfoModel;
use think\Cache;

class UserInfo extends UserInfoModel
{
    private $token;

    public function userInfo($data){
        $userInfo = $this->where(['phone'=>$data['phone'],'job_no'=>$data['job_no']])->find();
        if(empty($userInfo)){
            return false;
        }
        $this->token = $this->token($userInfo['id']);
        // 记录缓存, 7天
        Cache::set($this->token, $userInfo, 86400 * 7);
        return $userInfo['id'];
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($user_id)
    {
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt_user';
        return md5("{$timeStamp}_{$user_id}_{$guid}_{$salt}");
    }

    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }
    /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getUser($token)
    {
        $openId = Cache::get($token)['id'];
        return self::detail(['id' => $openId]);
    }
}